package pri.damai.xiaowu.usercenter.sysauth.application;

import org.springframework.stereotype.Service;
import pri.damai.xiaowu.common.core.tree.TreeUtils;
import pri.damai.xiaowu.usercenter.sysauth.covert.ResourceConverter;
import pri.damai.xiaowu.usercenter.sysauth.covert.SystemConverter;
import pri.damai.xiaowu.usercenter.sysauth.entity.SysResource;
import pri.damai.xiaowu.usercenter.sysauth.entity.System;
import pri.damai.xiaowu.usercenter.sysauth.service.SysResourceService;
import pri.damai.xiaowu.usercenter.sysauth.service.SystemService;
import pri.damai.xiaowu.usercenter.sysauth.service.impl.SysOrgServiceImpl;
import pri.damai.xiaowu.usercenter.vo.OrgVO;
import pri.damai.xiaowu.usercenter.vo.ResourceVO;
import pri.damai.xiaowu.usercenter.vo.SystemVO;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统权限应用服务
 * @Desc
 * @Author yxf
 * @Date 2022/3/17 21:58
 * 但行好事，莫问前程。
 */
@Service
public class SysAuthAppService {

    @Resource
    SystemService systemService;
    @Resource
    SysResourceService resourceService;
    @Resource
    SysOrgServiceImpl orgService;

    /**
     * 获取系统列表及菜单树
     *
     * @return java.util.List<pri.damai.xiaowu.usercenter.vo.SystemVO>
     * @author YangXinFu
     * @date 2022/7/20 14:08
     */
    public List<SystemVO> getSysWithMenu() {

        List<System> systemList = systemService.list();

        List<SystemVO> systemVOS = SystemConverter.convertToSysVO(systemList);

        List<SysResource> resourceList = resourceService.list();

        List<ResourceVO> resourceVOS = ResourceConverter.covertToResourceVO(resourceList);

        Map<Long, List<ResourceVO>> sysResourceMap = resourceVOS.stream()
                .collect(Collectors.groupingBy(ResourceVO::getSysId));

        return systemVOS.parallelStream()
                .peek(systemVO -> {
                    List<ResourceVO> sysResource = sysResourceMap.get(systemVO.getId());
                    List<ResourceVO> resourceTree = TreeUtils.toTreeNonRecursion(sysResource, TreeUtils.TOP_PARENT_ID);
                    systemVO.setMenuTree(resourceTree);
                })
                .collect(Collectors.toList());
    }

    public List<OrgVO> getOrgTree() {
        return orgService.getOrgTree();
    }
}
